﻿#include "WRWorkTcpCommServer.h"
#include "WRWorkTcpCommServerSocket.h"
#include "../WRWorkSwitchEvent.h"
#include "../WRWorkTcpCommConsts.h"

//初始化TCP服务上下文。
WRWorkTcpCommServer::WRWorkTcpCommServer()
{
    m_owner = 0;
    m_timer = 0;
}

//清理当前对象所占用的相关资源。
WRWorkTcpCommServer::~WRWorkTcpCommServer()
{
    if (isListening())
    {
        close();
    }
    if (m_timer)
    {
        killTimer(m_timer);
    }
    for(int i = 0; i < m_sockets.size(); ++i)
    {
        WRWorkTcpCommServerSocket* socket = m_sockets.at(i);
        socket->deleteLater();
    }
    m_sockets.clear();
}

//当有新连接后调用此方法。
void WRWorkTcpCommServer::incomingConnection(WRSocketDescriptor handle)
{
    WRWorkTcpCommServerSocket* socket = new WRWorkTcpCommServerSocket(this);
    socket->setSocketDescriptor(handle);
    m_sockets.append(socket);
    if (!m_timer)
    {
        m_timer = startTimer(WRWorkTcpComm::SessionTimeout);
    }
}

//处理定时器事件。
void WRWorkTcpCommServer::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == m_timer)
    {
        int index = 0;
        while(index < m_sockets.size())
        {
            WRWorkTcpCommServerSocket* socket = m_sockets.at(index);
            if (!socket->validate())
            {
                m_sockets.removeAt(index);
                socket->deleteLater();
                continue;
            }
            ++index;
        }

        if (!m_sockets.count())
        {
            killTimer(m_timer);
            m_timer = 0;
        }
    }
    else
    {
        QTcpServer::timerEvent(e);
    }
}

//事件处理。
bool WRWorkTcpCommServer::event(QEvent *e)
{
    if (WRWorkSwitchEvent::identify(e))
    {
        WRWorkSwitchEvent* e2 = static_cast<WRWorkSwitchEvent*>(e);
        m_owner = e2->params<WRWorkTcpCommService>();
        int* result = e2->result<int>();
        if (listen(QHostAddress::Any, m_owner->port()))
        {
            *result = WRErrors::None;
        }
        else
        {
            *result = -1;
            deleteLater();
        }
        e2->fulfil();
        return true;
    }
    return QTcpServer::event(e);
}

